package logging

import (
	"fmt"
	"os"
	"time"
)

var (
	LogSavePath       = "runtime/log/"
	LogSaveNamePrefix = "log"
	LogFileExt        = "log"
	TimeFormat        = "20160512"
)

//返回日志目录路径
func getLogFileDirPath() string {
	return fmt.Sprintf("%s", LogSavePath)
}

//返回日志的全路径
func getLogFileFullPath() string {
	logFileDirPath := getLogFileDirPath()
	fileName := fmt.Sprintf("%s%s.%s", LogSaveNamePrefix, time.Now().Format(TimeFormat))

	return fmt.Sprintf("%s%s", logFileDirPath, fileName)
}

func openLogFile(filepath string) *os.File {
	_, err := os.Stat(filepath)

	switch {
	case os.IsNotExist(err):
		mkDir()
	case os.IsPermission(err):
		log.Fatalf("permission:%v", err)
	}

	handle, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalf("Fail to open file:%v", err)
	}

	return handle
}

//创建目录
func MkDir() {
	dir, _ := os.Getwd()
	err := os.MkdirAll(dir+"/"+getLogFileFullPath(), os.ModePerm)
	if err != nil {
		panic(err)
	}
}
